local AddCSLuaFile, include, CreateConVar, game, GetConVar = AddCSLuaFile, include, CreateConVar, game, GetConVar

AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
AddCSLuaFile("player_sh.lua")

include("shared.lua")
include(game.GetMap() .. ".lua")
include("player_sh.lua")
include("player.lua")

function GM:Initialize()
	ZWeapons = ZWeapons or {}
	ZAmmo = ZAmmo or {}
	ZLoot = ZLoot or {}
	NPCSpawnPoints = NPCSpawnPoints or {}
	timer.Simple(10,function()
		self:SpawnStuff()
	end)
	timer.Create("LootRespawner", 120, 0, SpawnLoot)
end

function GM:OnNPCKilled(ent, attacker, inflictor)
	self.BaseClass:OnNPCKilled(ent,attacker,inflictor)
end

function GM:Think()
	self.LastThink = self.LastThink or 0
	if (self.LastThink + 30 < CurTime()) then
		self.LastThink = CurTime()
		for k,v in pairs(ents.GetAll()) do
			if v:GetClass() == "prop_ragdoll" then
				v:Remove()
			end
			if v:GetClass() == "sent_npcspawner" then
				v.active = 1
			end
		end
		for k,v in pairs(player.GetAll()) do
			if v:Alive() then
				v:EnergyConsume(1)
				if (v:Energy()<=0) then v:Kill() end
			end
		end
	end
end

function GM:SpawnStuff()
	for k,v in pairs(ents.FindByClass("prop_ragdoll")) do
		if (IsValid(v)) then v:Remove() end
	end
	for i=1,table.getn(NPCSpawnPoints) do
		local DoSpawn = true;
		for k,v in pairs(ents.FindInSphere(NPCSpawnPoints[i],50)) do
			if (v:GetClass() == "sent_npcspawner") then
				DoSpawn = false;
			end
		end
		if (DoSpawn) then
			local e = ents.Create("sent_npcspawner")
			e:SetPos(NPCSpawnPoints[i] + Vector(0,0,20))
			e:SetAngles(Angle(0,0,90))
			e.active = 1
			e.maximum = 1
			e.fadecorpse = 1
			e.toggleable = 0
			e:Activate()
			e:Spawn()
		end
	end
	SpawnLoot()
end

function SpawnLoot()
	for i=1,table.getn(ZLoot) do
		local DoSpawn = true
		for k,v in pairs(ents.FindInSphere(ZLoot[i],20)) do
			if v.IsLoot then DoSpawn = false end
		end
		if DoSpawn then
			local t = math.random(0,100)
			local classname = "weapon_crowbar"
			if (t > 33 and t < 66) then
				classname = ZWeapons[math.random(1,table.getn(ZWeapons))]
			end
			if (t < 33) then
				classname = ZAmmo[math.random(1,table.getn(ZAmmo))]
			end
			if (t > 66) then
				classname = ZOtherLoot[math.random(1,table.getn(ZOtherLoot))]
			end
			local e = ents.Create(classname)
			e:SetPos(ZLoot[i] + Vector(0,0,20))
			e.IsLoot = true
			e:Activate()
			e:Spawn()
		end
	end
end